package classes.classloader;

import java.util.Arrays;

public class ByteUtil {
    public static String bytes2Str(byte[] bytes, int offset, int length) {
        return new String(bytes, offset, length);
    }

    public static int bytes2int(byte[] bytes, int offset, int length) {
        if(length > 4 || offset < 0 || offset + length > bytes.length)
            throw new IllegalArgumentException();
        int r = 0;
        for (int i = 0; i < length; i++) {
            r = (r << 8) | bytes[offset + i];
        }
        return r;
    }

    public static byte[] int2Byte2(int i) {
        return new byte[]{(byte) (i >> 8), (byte) i};
    }

    public static int u1(byte b) {
        return b;
    }

    public static int u2(byte b1, byte b2) {
        return (b1 << 8) | b2;
    }

    /**
     * 数组中替换
     * @param source 源数组
     * @param offset 偏移量
     * @param length 原来数组的长度
     * @param newBytes 新数组
     */
    public static byte[] replaceBytes(byte[] source, int offset, int length, byte[] newBytes) {
        final int lengthNewBytes = newBytes.length, lengthSource = source.length;
        if(newBytes == null // 新的byte数组都不能为空
                || length < 0 // 原来的数组长度要大于0
                || offset >= lengthSource // 偏移量必须小于源数组的长度
                || offset + lengthNewBytes > lengthSource // 偏移量加上替换的数组长度要小于等于源数组长度
                || offset + length > lengthSource) // 偏移量加上原来数组长度要小于源数组长度
            throw new IllegalArgumentException();

        // 如果要替换的字符串的长度相等
        if(length == lengthNewBytes) {
            for (int i = 0; i < lengthNewBytes; i++) {
                source[offset + i] = newBytes[i];
            }
        } else {
            // 如果两个字符串长度不相等，要重新复制一个数组
            int newSize = lengthSource + (lengthNewBytes - length);
            byte[] bytes = new byte[newSize];
            System.arraycopy(source, 0, bytes, 0, offset);
            for (int i = 0; i < lengthNewBytes; i++) {
                bytes[offset + i] = newBytes[i];
            }
            System.arraycopy(source, offset + length, bytes, offset + lengthNewBytes, newSize - offset - lengthNewBytes);
            return bytes;
        }
        return source;
    }

    public static void main(String[] args) {
        byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        byte[] newBytes = {99, 98, 97, 96};
        bytes = ByteUtil.replaceBytes(bytes, 3, 6, newBytes);
        System.out.println(Arrays.toString(bytes));
    }
}
